'''
获取通用token
'''
import requests
import urllib3
from utils.config import host_port


class TokenManager():
    token = None

    @classmethod
    def getToken(cls):
        if cls.token is None:
            txt_session = TokenManager().getTxtSession()
            if txt_session == '':
                # txt也没有保存
                login_token = TokenManager().login('admin', 'admin')
                if login_token != '':
                    cls.token = login_token
            else:
                cls.token = txt_session

        return cls.token

    # 保存token到txt持久化
    def saveTxtSession(self, token):
        # 打开文件进行写操作
        with open('./get_token/token.txt', 'w') as f:
            f.write(token)

    # 清除token
    def clearTxtSession(self):
        # 打开文件进行写操作
        with open('./get_token/token.txt', 'w') as f:
            f.write('')

    # 获取txt的token
    def getTxtSession(self):
        # 打开文件进行读操作
        with open('./get_token/token.txt', 'r') as f:
            _token = f.read()
            return _token

    # 登录获取token
    def login(self, user, password):
        url = f'https://{host_port}/sys/login'
        header = {'Content-Type': 'application/json'}
        payload = {
            'username': user, 'password': password
        }
        # https不提示警告
        urllib3.disable_warnings()
        # verify=False 不验证https的证书
        r = requests.post(url, json=payload, headers=header, verify=False)
        # 解析数据
        json = r.json()
        code_ = json['code']
        if code_ == 0:
            token_ = json['token']
            # 保存token到txt
            TokenManager().saveTxtSession(token_)
            return token_
        else:
            # 清空token
            TokenManager().clearTxtSession()
            print(json['msg'])
            return ''


if __name__ == '__main__':
    tokn = TokenManager.getToken()
    print(f'token:{tokn}')
